package com.guoranhao.web.util;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("roundRobinBlance")
public class RoundRobinBlance {
	
	//当前选择index
	private volatile int c_index = 0;

	public Map<Integer, List<?>> groupSubList(List<?> collects, int group_num){
		Map<Integer, List<?>> retMap = new HashMap<Integer, List<?>>();
		int mod = collects.size() / group_num;
		int loop = 0;
		if(collects.size() % group_num == 0){
			loop = mod;
		}else{
			loop = mod + 1;
		}
		
		for(int i=1; i<=loop; i++){
			int fromIndex = (i-1) * group_num;
			int tail = i * group_num;
			int toIndex = tail >= collects.size()?collects.size():tail;	
			if((fromIndex < collects.size()) && (toIndex <= collects.size())){
				List<?> subList = collects.subList(fromIndex, toIndex);
				if(null != subList && subList.size() >0){
					retMap.put(i, subList);
				}
			}
		}
		return retMap;
	}
	
	public List<?> roundLoadBalance(Map<Integer, List<?>> sequences){
		if(sequences != null && sequences.size() > 0){
			int size = sequences.size();
			c_index++;
			if(c_index > size){
				c_index = 1;
			}
			return sequences.get(c_index);
		}
		return null;
	}
	
}
